package com.financing.platform.web.api;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;

import com.financing.platform.service.IFpFundBuynoticeService;
import com.financing.platform.service.IFpFundInfoService;
import com.financing.platform.service.IFpProjectTransferHisService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.StringUtil;
import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.FpFundBuynoticeDTO;
import com.financing.platform.dto.FpFundInfoDTO;
import com.financing.platform.dto.FpProjectTransferHisDTO;
import com.financing.platform.dto.UserInfoDTO;

/**
 * @Description: Controller
 * @author caojiayao
 * @version 1.0
 * @created 
 */
@Controller
@RequestMapping("/api/fund")
@Scope("prototype")
public class FpFundBuynoticeAction  extends BaseAction{
	@Autowired
	private IFpFundBuynoticeService fpFundBuynoticeService;
	@Autowired
	private IFpFundInfoService fpFundInfoService;
	@Autowired
	private IFpProjectTransferHisService fpProjectTransferHisService;
	
	@RequestMapping("/fdBuynoticeQueryList.shtml")
	@ResponseBody
	public ResultMap queryList(HttpServletRequest request,
			HttpServletResponse response,FpFundBuynoticeDTO dto,Pager pager) {
		try{
			log.info("Begin query fa user list!");
			
			dto.setBegin(pager.getStartIndex());
			dto.setPageSize(pager.getPageSize());
			
			int count = fpFundBuynoticeService.countFpFundBuynotice(dto);
			pager.setTotalCount(count);
			List<FpFundBuynoticeDTO> list = fpFundBuynoticeService.listFpFundBuynotice(dto);
			
			resultMap.setAttribute("list",list);
			resultMap.setAttribute("pager", pager);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			
			log.info("End querylist!");
		}catch(Exception e){
			log.error("queryList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
			
			return resultMap;
	}
	
	@RequestMapping("/fdBuynoticeAdd.shtml")
	@ResponseBody
	public ResultMap add(HttpServletRequest request,
			HttpServletResponse response,FpFundBuynoticeDTO dto) {
		try{
			log.info("Begin add info !");
			//判断是否有权限修改产品
			if(!isAccess(dto.getJjbm(),request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			DTOdateSet.setCreateInfo(dto, request.getSession());
			
			Integer id =fpFundBuynoticeService.insertFpFundBuynotice(dto);
			
			resultMap.getAttribute().put("id",id);
			
			if(id !=null && id >0){
			    resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
			log.info("End add fa user info !");
		}catch(Exception e){
			log.error("update fa user info error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
			return resultMap;
	}
	
	@RequestMapping("/fdBuynoticeUpdate.shtml")
	@ResponseBody
	public ResultMap update(HttpServletRequest request,
			HttpServletResponse response,FpFundBuynoticeDTO dto) {
		try{
			log.info("Begin update fa user info !");
			//判断是否有权限修改产品
			if(!isAccess(dto.getJjbm(),request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			DTOdateSet.setUpdateInfo(dto, request.getSession());
			Map map = getParameterMap(request);
			map.put("updateBy", dto.getUpdateBy());

			
			int count = fpFundBuynoticeService.updateFpFundBuynotice(map);
			
			resultMap.getAttribute().put("update count",count);
			if(count >0){
			    resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
			log.info("End update fa user info !");
		}catch(Exception e){
			log.error("update fa user info error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
			return resultMap;
				
	}
	
	@RequestMapping("/fdBuynoticeDelete.shtml")
	@ResponseBody
	public ResultMap delete(HttpServletRequest request,
			HttpServletResponse response,FpFundBuynoticeDTO dto) {
		try{
			log.info("Begin delete fa user info !");
			int count = fpFundBuynoticeService.delFpFundBuynotice(dto.getId());
			//判断是否有权限修改产品
			if(!isAccess(dto.getJjbm(),request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			resultMap.getAttribute().put("delete count",count);
			
			if(count > 0){
			    resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
			}
			log.info("End delete fa user info !");
		}catch(Exception e){
			log.error("delete fa user info error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
			
			return resultMap;
				
	}
	
	
	@RequestMapping("/fdBuynoticeDetail.shtml")
	@ResponseBody
	public ResultMap detail(HttpServletRequest request,
			HttpServletResponse response, FpFundBuynoticeDTO requestDto) {
		try{
			FpFundBuynoticeDTO dto = fpFundBuynoticeService.getFpFundBuynotice(requestDto);
			if(dto !=null){
				//获取转移后的 权限人
				FpFundInfoDTO bean = new FpFundInfoDTO();
				bean.setJjbm(dto.getJjbm());
				bean = fpFundInfoService.getFpFundInfo(bean);
				if(bean !=null){
					FpProjectTransferHisDTO tfdto = new FpProjectTransferHisDTO();
					tfdto.setPProjectId(bean.getId());
					tfdto.setpProjectType("02");//“02：私募” 
					String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(tfdto);
					if(!StringUtil.isNullOrEmptyStr(createBy)){
						dto.setCreateBy(createBy);
					}
				}
			}
			resultMap.setAttribute("detail", dto);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query friendshipLink list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;

	}
	/**
	 * 判断要修改的私募产品是否为当前用户所有
	 * @param projectId
	 * @param request
	 * @return
	 */
	private boolean isAccess(String jjbm,HttpServletRequest request){
		
		UserInfoDTO user = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
		
		//超级管理员具有所有产品的管理权限
		if(user.getUsername().equals("admin")){
			return true;
		}
		//权限扭转接收人
		FpFundInfoDTO bean = new FpFundInfoDTO();
		bean.setJjbm(jjbm);
		bean = fpFundInfoService.getFpFundInfo(bean);
		if(bean !=null){
			FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
			dto.setPProjectId(bean.getId());
			dto.setpProjectType("02");//“02：私募”
			String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
			if(!StringUtil.isNullOrEmptyStr(createBy)){
				//是否是扭转接收人
				if(user.getUsername().equals(createBy)){
					return true;
				}else{
					return false;
				}
			}
		}
		 if(bean!=null && bean.getCreateBy().equals(user.getUsername())){
			 return true;
		 }
		return false;
	}

/**
 * 从request中获得参数Map，并返回可读的Map
 * 
 * @param request
 * @return
 */
@SuppressWarnings("unchecked")
public  Map getParameterMap(HttpServletRequest request) {
    // 参数Map
    Map properties = request.getParameterMap();
    // 返回值Map
    Map returnMap = new HashMap();
    Iterator entries = properties.entrySet().iterator();
    Map.Entry entry;
    String name = "";
    String value = "";
    while (entries.hasNext()) {
        entry = (Map.Entry) entries.next();
        name = (String) entry.getKey();
        Object valueObj = entry.getValue();
        if(null == valueObj){
            value = "";
        }else if(valueObj instanceof String[]){
            String[] values = (String[])valueObj;
            for(int i=0;i<values.length;i++){
                value = values[i] + ",";
            }
            value = value.substring(0, value.length()-1);
        }else{
            value = valueObj.toString();
        }
        returnMap.put(name, value);
    }
    return returnMap;
}
}